<?php

/**
 * This is the model class for table "floder".
 *
 * The followings are the available columns in table 'floder':
 * @property string $id
 * @property string $name
 * @property string $uid
 * @property string $create_time
 * @property string $type
 * @property string $note
 */
class Floder extends Base
{
    public static $type_map = array(
        'image' => '相册',
        'video' => '视频集'
    );
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'floder';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('type', 'required'),
			array('name', 'length', 'max'=>20),
			array('uid, create_time', 'length', 'max'=>10),
			array('type', 'length', 'max'=>5),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, name, uid, create_time, type, note', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'admin'=>array(self::BELONGS_TO, 'Admin', 'uid','select'=>'username'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name' => '名称',
			'uid' => '创建人id',
			'create_time' => '创建时间',
			'type' => '类型',
			'note' => '描述',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('uid',$this->uid,true);
		$criteria->compare('create_time',$this->create_time,true);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('note',$this->note,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Floder the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    /**
     * 添加文件夹
     */
    public function create($data) {
        if (empty($data['name']) || empty($data['type'])) {
            $this->addError('create', '参数非法');
            return false;
        }
       /* $attr = array(
            'name' => $data['name'],
            'type' => $data['type'],
        );
        $find_ret = $this->findByAttributes($attr);
        if ($find_ret !== null) {
            $this->addError('create', '名称已存在');
            return false;
        }*/
        if (!empty($data['thumb_sign'])) {
            $this->thumb_src = $this->getProcessImg($data['thumb_sign']);
        }
        $this->note = $data['note'];
        $this->name = $data['name'];
        $this->type = $data['type'];
        $this->pid = $data['pid'];
        $this->create_time = time();
        $this->app_id = $data['app_id'];
        $this->uid = Yii::app()->session['auth']['id'];
        return $this->save();
    }

    /**
     * 获取压缩之后的图片路径
     * @param $thumb_sign string 图片上传标识
    */
    public function getProcessImg($thumb_sign) {
        //压缩相关参数
        $params = Yii::app()->params['upload']['imgProcess'];
        if (!isset($params['floder'])) {
            $this->addError('add', '压缩参数未配置');
            return false;
        }
        $thumb_src = Image::model()->moveFile($thumb_sign);
        if ($thumb_src === false) {
            $this->addError('add', Image::model()->getErrors());
            return false;
        }
        $upload_params = $params['floder'];
        $root_path = Yii::getPathOfAlias('webroot');
        //压缩相对目录
        $process_dir = '/static/'.$params['directory'] . '/' . date('Y-m-d') . '/';
        $out_dir = $root_path . $process_dir;   //压缩绝对目录
        if (!is_dir($out_dir)) {
            mkdir($out_dir, 0777, true);
        }
        $witdh = $upload_params['width'];
        $height = $upload_params['height'];
        $source = $root_path .  $thumb_src;
        try {
            $img_tool = new ImageTool($source, $out_dir);
            //压缩宽度、压缩高度、是否保存
            $process_sign = $img_tool->compressImage($witdh, $height)->getProcessPath();
            return $process_dir  . $process_sign;
        } catch (CException $e) {
            $this->addError('add', $e->getMessage());
            return false;
        }
    }

    public function pageListCondition(CDbCriteria $criteria) {
        if (!empty($this->pid)) {
            $criteria->addCondition("pid={$this->pid}");
        } else if ($this->pid !== null) {
            //微信端首页50个二级目录
            $criteria->addCondition("pid>0 and type='{$this->type}'");
            $criteria->limit = 50;
        }else {
            $criteria->addCondition("type='{$this->type}' and pid=0");
        }
    }

    /**
     * 设置分页的其他操作，排序，分类，等操作(依赖注入的形式来改变$criteriad对象属性)
     * @param $criteria CDbCriteria $criteriad查询对象
     * @return null
     */
    protected function pageListOpt(CDbCriteria $criteria) {
        $criteria->select = 'id,FROM_UNIXTIME(create_time) as create_time,name,note,uid,thumb_src,type,app_id';
        $criteria->order = 'id desc';
    }

    /**
     * 获取文件夹
     * @param $type string 文件夹类型，默认是相册
     * @return array 所有父文件夹、子文件夹
    */
    public function getSubFloder($type = 'image') {
        $sub = $parent = array();
        $default = null;
        $all_floder = $this->findAllByAttributes(array('type'=>$type));
        foreach ($all_floder as $floder) {
            if ($floder->pid == 0) {
                $parent[$floder->id] = $floder;
            } else {
                if ($default === null) {
                    $default = $floder;
                }
                $sub[$floder->pid][] = $floder;
            }
        }
        return array(
            'parent' => $parent,
            'sub' => $sub,
            'default' =>$default
        );
    }

    /**
     * 获取所有目录，以父目录、子目录的结构返回
     * @return array 目录、子目录的结构
     */
    public function getParentFloder() {
        $parent_floder = $this->findAll('type=:type and pid=0', array(':type' => $this->type));
        return $parent_floder;
    }

    /**
     * 删除目录
     * @return bool 删除成功/失败
     */
    public function remove() {
        $root_path = Yii::getPathOfAlias('webroot');  //网站根目录
//        $upload_src = $root_path . $this->upload_src;
        $thumb_src = $root_path . $this->thumb_src;

        /*if (!empty($upload_src) && file_exists($upload_src)) {
            $is_success = unlink($upload_src);
            if (!$is_success) {
                $this->addError('remove', '图片文件删除失败');
                return false;
            }
        }*/
        //如果缩略图图片文件存在、删除图片文件
        if (!empty($this->thumb_src) && file_exists($thumb_src)) {
            $is_success = unlink($thumb_src);
            if (!$is_success) {
                $this->addError('remove', '缩略图文件删除失败');
                return false;
            }
        }
        //如果有子目录，递归删除子目录
        $sub_list = $this->findAll('pid=:pid', array(':pid'=>$this->id));
        if (!empty($sub_list)) {
            foreach ($sub_list as $sub) {
                $sub->remove();
            }
        }
        //如果有图片或者视频，删除所有的图片或视频
        if ($this->type == 'image') {
            $image_list = Image::model()->findAll('pid=:pid', array(':pid' => $this->id));
            if (!empty($image_list)) {
                foreach ($image_list as $image) {
                    $image->remove();
                }
            }
        } else {
            $video_list = Video::model()->findAll('pid=:pid', array(':pid' => $this->id));
            if (!empty($video_list)) {
                foreach ($video_list as $video) {
                    $video->remove();
                }
            }
        }
        return $this->delete();
    }
}
